package oleg.util;

/**
 * Copyright 2008,2009 Oleg Frenkel
 *
 * This file is part of PerfectSearch.
 *
 * PerfectSearch is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * PerfectSearch is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with PerfectSearch.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.util.Vector;

public class Collections
{
  public static int binarySearchString(Vector vector, String key) {
    int low = 0;
    int high = vector.size()-1;

    while (low <= high) {
      int mid = (low + high) >> 1;
      String midVal = (String)vector.elementAt(mid);
      int cmp = midVal.compareTo(key);

      if (cmp < 0)
        low = mid + 1;
      else if (cmp > 0)
        high = mid - 1;
      else
        return mid; // key found
    }
    return -(low + 1);  // key not found
  }

  public static int binarySearch(String[] vector, String key) {
    int low = 0;
    int high = vector.length-1;

    while (low <= high) {
      int mid = (low + high) >> 1;
      String midVal = (String)vector[mid];
      int cmp = midVal.compareTo(key);

      if (cmp < 0)
        low = mid + 1;
      else if (cmp > 0)
        high = mid - 1;
      else
        return mid; // key found
    }
    return -(low + 1);  // key not found
  }

  public static void sortString(Vector list) {
    String a[] = new String[list.size()];
    list.copyInto(a);
    Arrays.sort(a);
    for (int j=0; j<a.length; j++) {
	    list.setElementAt(a[j], j);
    }
  }

  public static void sortObjects(Vector list, Comparator c) {
    Object a[] = new Object[list.size()];
    list.copyInto(a);
    Arrays.sort(a, c);
    for (int j=0; j<a.length; j++) {
	    list.setElementAt(a[j], j);
    }
  }
}